package com.hymjweb.demo.hymj.finance_manage.invoice_register.detail.service;

import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.finance_manage.invoice_register.detail.bean.CwInvoiceRegisterDetailPojo;
import com.hymjweb.demo.hymj.finance_manage.invoice_register.detail.mapper.CwInvoiceRegisterDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class CwInvoiceRegisterDetailService extends BaseService {

    @Autowired
    private CwInvoiceRegisterDetailMapper cwInvoiceRegisterDetailMapper;

    @Transactional(rollbackFor = {Exception.class})
    public int batchInsert(List<CwInvoiceRegisterDetailPojo> detailPojoList) throws Exception {
        if (detailPojoList == null || detailPojoList.isEmpty()) {
            throwException("批量添加发票明细对象参数!");
        }
        int affectRows = 0;
        for (CwInvoiceRegisterDetailPojo pojo : detailPojoList) {
            affectRows += this.insert(pojo);
        }
        return affectRows;
    }


    @Transactional(rollbackFor = {Exception.class})
    public int insert(CwInvoiceRegisterDetailPojo pojo) throws Exception {
        if (pojo == null) {
            throwException("添加发票明细对象参数!");
        }
        return cwInvoiceRegisterDetailMapper.insert(pojo);
    }


    /**
     * 发票号码保存
     *
     * @param param
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int saveInvoiceCode(Map param) throws Exception {
        if (param == null || param.isEmpty()) {
            throwException("发号码保存参数错误!");
        }

        String invoiceDetailIds = DataTypeUtil.toStringObject(param.get("invoiceDetailIds"));
        String invoiceCode = DataTypeUtil.toStringObject(param.get("invoiceCode"));

        if (DataTypeUtil.isEmptyStr(invoiceDetailIds) || DataTypeUtil.isEmptyStr(invoiceCode)) {
            throwException("发号码保存参数错误!");
        }

        String[] invoiceDetailIdArray = invoiceDetailIds.split(",");

        if (invoiceDetailIdArray == null || invoiceDetailIdArray.length == 0) {
            throwException("发号码保存参数错误!");
        }

        int affectRows = 0;
        for (String detailId : invoiceDetailIdArray) {
            CwInvoiceRegisterDetailPojo detailPojo = cwInvoiceRegisterDetailMapper.queryPojoById(detailId);
            detailPojo.setInvoiceCode(invoiceCode);
            affectRows += cwInvoiceRegisterDetailMapper.update(detailPojo);
        }

        return affectRows;
    }
}
